package cn.fz.luck.saas.service.serviceImpl;

import cn.fz.luck.saas.bean.SysStatusEnum;
import cn.fz.luck.saas.mapper.SysUserMapper;
import cn.fz.luck.saas.model.SysUser;
import cn.fz.luck.saas.service.SysUserService;
import cn.fz.luck.saas.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * Created by zhuangqi on 17-7-6.
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public SysUser getByUserName(String userName) {
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        return sysUserMapper.selectOne(sysUser);
    }

    @Override
    public SysUser insert(SysUser user) {
        final String userName = user.getUserName();
        if (this.getByUserName(userName)!=null) throw new RuntimeException("该用户已存在");
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        final String rawPassword = user.getPassword();
        user.setPassword(encoder.encode(rawPassword));
        user.setUserId(UUID.UU64());
        user.setLastLogin(new Date());
        sysUserMapper.insert(user);
        return user;
    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.updateByPrimaryKey(sysUser);
    }

    @Override
    public void updateStatus(String userId, SysStatusEnum statusEnum) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        sysUser.setStatus(statusEnum.getCode());
        sysUserMapper.updateByPrimaryKey(sysUser);
    }
}
